package dm.api;

import org.apache.log4j.Logger;

import dm.bsi.Deployment;
import dm.bsi.Image;
import dm.bsi.Log;
import dm.bsi.WDeployment;
import indi.zjh.dp.access.Api;
import indi.zjh.dp.access.ApiContext;
import indi.zjh.dp.db.Configuration;
import indi.zjh.dp.db.Session;
import indi.zjh.dp.orm.Query;
import indi.zjh.dp.orm.Result;
import indi.zjh.dp.type.GSet;
import indi.zjh.dp.verify.CharNotEmptyRule;
import indi.zjh.dp.verify.CharSetRule;
import indi.zjh.dp.verify.Check;
import indi.zjh.dp.verify.StringSetRule;
import indi.zjh.dp.verify.ValueRangeRule;

public class UpgradeDeploymentApi extends Api {
	private static Logger logger = Logger.getLogger(UpgradeDeploymentApi.class);
	
	@Override
	public void process(ApiContext ctx) throws Exception {
		// TODO Auto-generated method stub
		Session session = Configuration.getSessionFactory().createSession();
		try
		{
			String name = ctx.getRequestParamValue("name");
			String modeStr = ctx.getRequestParamValue("mode");
			Check.data(name).desc("请输入合法存在的部署名称").rule(new CharSetRule(CharSetRule.NAME_SET));
			Check.data(modeStr).desc("请输入合法的部署模式mode, w; ms; mss").rule(new StringSetRule(GSet.createStringSet().addString("w").addString("ms").addString("mss")));
			
			int mode = Deployment.MODE_WORKER;
			String workerImageName = null;
			if(modeStr.equals("w"))
			{
				mode = Deployment.MODE_WORKER;
				workerImageName = ctx.getRequestParamValue("workerImage").trim();
				Check.data(workerImageName).desc("请输入镜像名称workImage").rule(new CharNotEmptyRule());
				
				Query<WDeployment> query = new Query<WDeployment>(session);
				Result<WDeployment> result = query.find(WDeployment.class).extend(WDeployment.class, Deployment.class, "`name` = '"+name+"'").result();
				if(result.count() == 0)
				{
					throw new Exception("部署["+name+"]不存在");
				}
				
				WDeployment deployment = result.iterator().next();
				
				Image workderImage = Image.getImageByName(session, workerImageName);
				if(workderImage == null)
				{
					workderImage = new Image();
					workderImage.setName(workerImageName);
					session.save(workderImage);
				}
				deployment.getImage().clear();
				deployment.getImage().add(workderImage);
				session.save(deployment);
				
				Log.info(session, deployment, "设置部署升级镜像 = "+workerImageName);				
			}

			session.commit();
			
			ctx.writeResponse("OK");
		}
		catch(Exception e)
		{
			ctx.writeResponse("FAIL:"+e.getMessage());
			session.rollback();
			e.printStackTrace();
		}
		finally {
			session.close();
		}
	}

}
